package secondStage.part4.字符流;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @ClassName: [CopyFileDemo]
 * @Description: 复制文件加入异常处理
 * @Author: [黄劲松]
 * @CreateDate: [2021-04-05]
 * @Version: [v1.0]
 */
/*
    复制文件加入异常处理
 */
public class CopyFileDemo {
    public static void main(String[] args) {
    }
    //4、JDK1.9改进方案（自动释放资源）
   /* public static void method4() throws IOException {
        FileReader fr = new FileReader("fr.txt");
        FileWriter fw = new FileWriter("fw.txt");
        try (fr;fw) {//由于我在用的JDK是1.8所以报错
            char[] chs = new char[1024];
            int len;
            while ((len = fr.read()) != -1) {
                fw.write(chs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/

    //3、JDK1.7改进方案（自动释放资源）
    public static void method3() {
        try (
                FileReader fr = new FileReader("fr.txt");
                FileWriter fw = new FileWriter("fw.txt");
        ) {
            char[] chs = new char[1024];
            int len;
            while ((len = fr.read()) != -1) {
                fw.write(chs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //2、try.....catch.....finaly处理
    public static void method1() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader("fr.txt");
            fw = new FileWriter("fw.txt");

            char[] chs = new char[1024];
            int len;
            while ((len = fr.read()) != -1) {
                fw.write(chs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //1、抛出处理
    public static void method() throws IOException {
        FileReader fr = new FileReader("fr.txt");
        FileWriter fw = new FileWriter("fw.txt");

        char[] chs = new char[1024];
        int len;
        while ((len = fr.read()) != -1) {
            fw.write(chs, 0, len);
        }
        fw.close();
        fr.close();
    }
}
